package com.example.contactfragment;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.boyuan.huijiaoyu.BaseActivity;
import com.boyuan.huijiaoyu.HomeContactDeail1Activity;
import com.boyuan.huijiaoyu.HomeContactDeail2Activity;
import com.boyuan.huijiaoyu.R;
import com.example.newfragment.DetailPerson;
import com.magicsoft.app.helper.SharePreferenceHelper;
import com.magicsoft.app.helper.StringUtils;
import com.magicsoft.app.helper.ToastHelper;
import com.magicsoft.app.wcf.listener.GetOneRecordListener;
import com.ttcaca.cas.android.client.model.User;

/**
 * 通讯录搜索
 * 
 * @author liqingjun
 * 
 */
public class HomeContactSearchActivity extends BaseActivity implements
		OnClickListener {

	// 返回取消
	private Button btnBack;
	// 账号
	private User account;
	// 搜索历史
	private LinearLayout lin_history;
	private List<String> historyDatas = new ArrayList<String>();
	private HomeContactSearchHistoryAdapter historyAdapter;
	private ListView listview_history;
	// 在分类下搜索
	private LinearLayout lin_classify;
	// 组织结构
	private LinearLayout lin_org;
	// 通讯录
	private LinearLayout lin_contact;
	// 搜索历史，分类搜索布局
	private LinearLayout lin_search_history;
	// 搜索結果
	private ArrayList<SearchPeople> searchDatas = new ArrayList<SearchPeople>();
	private HomeContactSearchAdapter searchAdapter;
	private ListView listview_result;
	private EditText et_content;
	private boolean isSelectFromPhoneContact = false;
	private ContactService contactService;
	String yonghuID;
	private DetailPerson homeContactCommonEntity;
	private String uid;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home_contact_search);
		SharedPreferences sp = getSharedPreferences("a.xml", 0);
		yonghuID = sp.getString("id", "");
		prepareView();
//		prepareData();
	}

	private void prepareView() {
		// 返回取消
		btnBack = (Button) findViewById(R.id.btnBack);
		btnBack.setOnClickListener(this);

		et_content = (EditText) findViewById(R.id.edit_search);
		et_content.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				getSearchResult(s.toString());
			}
		});

		et_content.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				// TODO Auto-generated method stub
				if (actionId == EditorInfo.IME_ACTION_SEARCH) {
					String key = et_content.getText().toString();
					getSearchResult(key);

				}
				return true;
			}
		});
		// //搜索历史，分类搜索布局
		lin_search_history = (LinearLayout) findViewById(R.id.lin_search_history);
		// 搜索历史
		lin_history = (LinearLayout) findViewById(R.id.lin_history);
		listview_history = (ListView) findViewById(R.id.listview_history);

//		TextView footerTextView = new TextView(HomeContactSearchActivity.this);
//		footerTextView.setTextSize(16);
//		footerTextView.setTextColor(getResources().getColor(
//				R.color.home_tab_txt_sel_color));
//		footerTextView.setText("清除历史记录");
//
//		listview_history.addFooterView(footerTextView);

		historyAdapter = new HomeContactSearchHistoryAdapter(
				HomeContactSearchActivity.this, historyDatas);
		listview_history.setAdapter(historyAdapter);
		listview_history.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub

				if (position == historyDatas.size()) {
					SharePreferenceHelper.saveContactSearchHistoryList(
							getApplicationContext(), new ArrayList<String>(),
							account.getUid());

					historyDatas.clear();
					historyAdapter.notifyDataSetChanged();
					lin_history.setVisibility(View.GONE);
				} else {
					et_content.setText(historyDatas.get(position));
					// getSearchResult(historyDatas.get(position));
				}
			}
		});
//		// 分类搜索
//		lin_classify = (LinearLayout) findViewById(R.id.lin_classify);
//		// 组织结构
//		lin_org = (LinearLayout) findViewById(R.id.lin_org);
//		lin_org.setOnClickListener(this);
//		// 通讯录
//		lin_contact = (LinearLayout) findViewById(R.id.lin_contact);
//		lin_contact.setOnClickListener(this);
		// 搜索結果
		listview_result = (ListView) findViewById(R.id.listview_result);
		searchAdapter = new HomeContactSearchAdapter(
				HomeContactSearchActivity.this, searchDatas);
		listview_result.setAdapter(searchAdapter);
		listview_result.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				setIntent(position);
			}
		});
	}

	private void prepareData() {

		account = SharePreferenceHelper.GetAccount(getApplicationContext());

		Intent intent = getIntent();

		isSelectFromPhoneContact = intent.getBooleanExtra("isOnlyShowHistory",
				false);

		if (isSelectFromPhoneContact) {
			lin_org.setSelected(false);
			lin_contact.setSelected(true);
		} else {
			lin_org.setSelected(true);
			lin_contact.setSelected(false);
		}

		List<String> datas = SharePreferenceHelper.getContactSearchHistoryList(
				getApplicationContext(), account.getUid());

		if (datas != null && datas.size() > 0) {
			historyDatas.addAll(datas);
			historyAdapter.notifyDataSetChanged();
			lin_history.setVisibility(View.VISIBLE);
		} else {
			lin_history.setVisibility(View.GONE);
		}
	}

	private void setIntent(int position) {
		if (account != null) {

			String keyword = et_content.getText().toString();

			List<String> datas = SharePreferenceHelper
					.getContactSearchHistoryList(getApplicationContext(),
							account.getUid());

			if (datas != null) {
				if (!datas.contains(keyword)) {
					if (datas.size() > 10) {
						datas.remove(0);
					}
					datas.add(keyword);
				}
			} else {
				datas = new ArrayList<String>();
				datas.add(keyword);
			}

			SharePreferenceHelper.saveContactSearchHistoryList(
					getApplicationContext(), datas, account.getUid());

			historyDatas.addAll(datas);
			historyAdapter.notifyDataSetChanged();
			if (datas.size() > 0) {
				lin_history.setVisibility(View.VISIBLE);
			} else {
				lin_history.setVisibility(View.GONE);
			}
		}

		SearchPeople contactEntity = (SearchPeople) searchDatas
				.get(position);
		uid = contactEntity.getAccount_id();
		getContactDetail(uid);
//		Intent intent = new Intent(HomeContactSearchActivity.this,
//				HomeContactDeail2Activity.class);
//		intent.putExtra("uid", contactEntity.getAccount_id());
//		startActivity(intent);
	}

	private void getSearchResult(String keyword) {

		if (StringUtils.isNotEmpty(keyword)) {

			if (contactService == null) {
				contactService = new ContactService(getApplicationContext());
			}

			contactService.getSearchPeople(keyword,
					new GetOneRecordListener<List<SearchPeople>>() {

						@Override
						public void onFinish(List<SearchPeople> data) {
							// TODO Auto-generated method stub

							listview_result.setVisibility(View.VISIBLE);
							lin_search_history.setVisibility(View.GONE);

							searchDatas.clear();
							if (data != null) {
								searchDatas.addAll(data);
							}

							searchAdapter.notifyDataSetChanged();
						}

						@Override
						public void onFailed(String Message) {
							// TODO Auto-generated method stub
							searchDatas.clear();
							searchAdapter.notifyDataSetChanged();
							listview_result.setVisibility(View.GONE);
							lin_search_history.setVisibility(View.VISIBLE);
							ToastHelper.showMsg(HomeContactSearchActivity.this,
									Message, false);
						}
					});

		} else {
			searchDatas.clear();
			searchAdapter.notifyDataSetChanged();
			listview_result.setVisibility(View.GONE);
			lin_search_history.setVisibility(View.VISIBLE);

		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btnBack:
			finish();
			break;
//		case R.id.lin_org:
//			isSelectFromPhoneContact = false;
//			lin_org.setSelected(true);
//			lin_contact.setSelected(false);
//			break;
//		case R.id.lin_contact:
//			isSelectFromPhoneContact = true;
//			lin_org.setSelected(false);
//			lin_contact.setSelected(true);
//			break;
		default:
			break;
		}
	}

	@Override
	public void backClicked() {
		if (isShowingLoading()) {
			hideLoading();
		} else {
			isBackAllowed = true;
		}
	}
	
	private void getContactDetail(final String contactsID) {


		if (contactService == null) {
			contactService = new ContactService(getApplicationContext());
		}

		showLoading(getString(R.string.loading_data));

		contactService.getContactdetail(yonghuID, contactsID,
				new GetOneRecordListener<DetailPerson>() {

					@Override
					public void onFinish(DetailPerson data) {
						// TODO Auto-generated method stub
						hideLoading();
						homeContactCommonEntity = data;
						if(homeContactCommonEntity.getIs_common().equals("1")||homeContactCommonEntity.getIs_favorite().equals("1")){
							Intent intent = new Intent(HomeContactSearchActivity.this,HomeContactDeail2Activity.class);
							intent.putExtra("uid", uid);
							intent.putExtra("homeContactDetailEntity", homeContactCommonEntity);
							intent.putExtra("titleback", "通讯录");
							startActivity(intent);
						}else{
							Intent intent = new Intent(HomeContactSearchActivity.this,HomeContactDeail1Activity.class);
							intent.putExtra("homeContactDetailEntity", homeContactCommonEntity);
							intent.putExtra("yonghuID", yonghuID);
							intent.putExtra("uid", uid);
							intent.putExtra("titleback", "通讯录");
							startActivity(intent);
						}

					}

					@Override
					public void onFailed(String Message) {
						// TODO Auto-generated method stub
						hideLoading();
						ToastHelper.showMsg(HomeContactSearchActivity.this,
								Message, false);
					}
				});
	}

}
